// This module is licensed and may be used under the terms of the
//  GPL, GNU General Public License, V3 or later, http://www.gnu.org/licenses/gpl.html
//
// Please contact the author if you need another license.
// This module is provided "as is", without warranties of any kind.

import java.net.*;
import java.io.*;

/**
 * Generic network communications module with lower-level functionality
 * 
 * Module capable of sending and recieving commands to and from a remote server
 *
 * Project home page: http://code.google.com/p/simple-net-comm/
 * Author: Jonathan Bonazza
 * License: GPL
 */
public class DefaultNetComm extends NetComm
{
	protected BufferedReader br;		//buffered reader used to receive messages from the server
	protected DataOutputStream dos;		//binary output stream used to send messages to a server

	public DefaultNetComm(String uid, String addr, int port) throws IOException
	{
		super(uid, addr, port);

		br = new BufferedReader(new InputStreamReader(soc.getInputStream()));
		dos = new DataOutputStream(soc.getOutputStream());
	}

	/**
	 * @brief: sends a message to the server
	 * @param: the message to send to the server
	 * @return: void
	 */
	public void sendMessage(String msg) throws IOException
	{
		byte[] bytes = (msg + "\n").getBytes();
		dos.writeBytes(msg+"\n");
		System.out.println("<<< " + msg + " (" + bytes.length + " bytes)");
	}

	/**
	 * @brief: recieves a message from the server
	 * @param: void
	 * @return: the recieved message
	 */
	public String recieveMessage() throws IOException
	{
		String line = br.readLine();
		
		//If something was read, print it to the console
		if(line != null)
			System.out.println(">>> " + line + " (" + line.getBytes().length + " bytes)");
	
		return line;
	}

	/**
	 * @brief: convenience method for expecting a certain string to be read
	 * @param: the expected string
	 * @return: void
	 */
	public void expect(String str) throws IOException
	{
		//recieve a message and if it doesn't start with the expected string,
		//provide an error message in the console and throw an exception		
		if(!recieveMessage().startsWith(str))
		{
			System.out.println("Expected response not found.");
			throw new IOException();
		}
	}
}
